package 网络编程项目.login.utiles;


import 网络编程项目.login.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class sqlUtil {

  //通过用户名获取用户
  public static User getUserByID(String userid) {
    User user = new User();
    try {
      Connection connection = ConnectSingleton.getConnection();
      String sql = "select * from user where userid=?";
      PreparedStatement statement = connection.prepareStatement(sql);
      statement.setString(1, userid);
      ResultSet resultSet = statement.executeQuery();
      if (resultSet.next()) {
        user = userUtil.getUserByResultSet(resultSet);
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return user;
  }

  //获取锁定的用户
  public static List<User> getNonLockUser() {
    List<User> users = new ArrayList<>();
    try {
      Connection connection = ConnectSingleton.getConnection();
      String sql = "select * from user where state=0";
      PreparedStatement statement = connection.prepareStatement(sql);
      ResultSet resultSet = statement.executeQuery();
      while (resultSet.next()) {
        users.add(userUtil.getUserByResultSet(resultSet));
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return users;
  }

  //插入用户
  public static boolean insertUser(User user) {
    boolean execute = false;
    Connection connection = ConnectSingleton.getConnection();
    try {
      PreparedStatement statement = connection.prepareStatement(userUtil.getInsertSql(user));
      statement.execute();
      execute = true;
    } catch (SQLException e) {
      execute = false;
    }
    return execute;
  }

  //修改用户
  public static boolean updateUser(User user) {
    Connection connection = ConnectSingleton.getConnection();
    boolean execute = false;
    try {
      PreparedStatement statement = connection.prepareStatement(userUtil.getUpdateSql(user));
      execute = statement.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return execute;
  }
}
